#!C:/soft/php/php-cgi.exe

<?PHP

function readData($filename,&$q,&$qn) {
  $f=fopen($filename, 'r');
  if ($f == FALSE) {
    die("can not open file [".$filename."]");
  }
  $qn = 0;
  while (($buf = fgets($f)) != false) {
    if (strlen($buf) > 2) {
      $q[$qn++] = $buf;
    }
  }
  fclose($f);
}

$qfile=$_GET["q"];
$mfile=$_GET["m"];
if ( isset($qfile) ) {
  $qn = 0;
  readData($qfile,$q,$qn);
} else {
  die("usage: anketa.php?q=file_with_questions&m=file_with_answer_types");
}

if ( isset($mfile) ) {
  readData($mfile,$a,$an);
} else {
  $an = 3;
  $a[0] = 'я это хорошо знаю, слушать не хочу';
  $a[1] = 'я это плохо знаю, но слушать не хочу';
  $a[2] = 'я хотел бы это услышать';
}

?>

<head>
  <title>Анкета [<?PHP print($qfile); ?>]</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <link rel="stylesheet" href="index.css"/>
</head>

<?PHP

if ( isset($_POST["secretname"]) ) {
  $name=$_POST['secretname'];

  $ans = "";
  for ($i = 0; $i < $qn; $i++) {
    if ($q[$i][0] != '#') {
      if (isset($_POST['group'.$i])) {
        $ans = $ans.$_POST['group'.$i];
      }  else {
        $ans = $ans.'-';
      }
    }
  }

  print('TRY TO SAVE ANSWERS<br>Your name = '.$name.'<br>Answer = '.$ans.'<br>'."\n");
  if (strlen(trim($name)) == 0) {
    printf('<span style="color: red;">Error: name is empty. Answers are not saved.</span><br>'."\n");
    printf('Press backspace to change it.');
    exit;
  }
  $f=fopen($qfile.'.ans', 'a+');
  if ($f == FALSE) {
    die("can not open file with answers\n");
  }
  fprintf($f, "%s %s\n", $ans, $name);
  fclose($f);

  printf('<span style="color: green;">Your answer is ok!</span><br>'."\n");
  exit;
}

?>

<body>

<h2>Анкета [<?PHP print($qfile.', '.$mfile); ?>]</h2>

<form action="anketa.php?<?PHP print('q='.$qfile); ?>" method="post">
<?PHP
  for ($j = 0; $j < $an; $j++) {
    print("$j"." - ".$a[$j]."<br>\n");
  }
?>
<br>

<table border=1 cellspacing=0 cellpadding=3>
  <tr><td></td><td><b>Your name:</b> <span style="color: red;">(обязательное поле)</span></td><td><input type="text" name="secretname" width=70></td></tr>

<?PHP
$num = 0;
for ($i = 0; $i < $qn; $i++) {
  print('  <tr>');
  if ($q[$i][0] == '#') {
    print('<td colspan=3 width=* align=center style="background: #DDDDDD;"><span style="color: blue; font-weight: bold;">'.substr($q[$i], 1).'</span></td>');
  } else {
    $num++;
    print('<td>'.$num.'</td><td>'.$q[$i].'</td><td><p>');
    for ($j = 0; $j < $an - 1; $j++) {
      print('<input type="radio" name="group'.$i.'" value="'.$j.'" width=10>'.$j);
    }
    print('<input type="radio" name="group'.$i.'" value="'.$j.'" width=10 checked="checked">'.$j);
  }
  print("</td></tr>\n");
}
?>
</table>
<br>
<input type="submit" value="Finish him!">

</form>

</body>
